<template>
<div>
  <a href="#" @click="changeType($event, TYPE.LOGIN)">登录</a> | <a href="#" @click="changeType($event, TYPE.REGISTER)">注册</a>
  <div v-if="curType === TYPE.LOGIN">
    登录
    <br>
    用户名：<input type="text" v-model="loginObj.username">
    <br>
    密码：<input type="password" v-model="loginObj.password">
    <br>
    <button @click="handleLogin">登录</button>
  </div>
  <div v-else-if="curType === TYPE.REGISTER">
    注册
    <br>
    用户名：<input type="text" v-model="registerObj.username">
    <br>
    昵称：<input type="text" v-model="registerObj.nickname">
    <br>
    密码：<input type="password" v-model="registerObj.password">
    <br>
    <button @click="handleRegister">注册</button>
  </div>
</div>
</template>

<script>
import {register,login} from '../../apis/login'
const TYPE = {
  LOGIN: 0,
  REGISTER: 1
}
export default {
  name: "index",
  data: _ => ({
    TYPE,
    curType: TYPE.LOGIN,
    registerObj: {
      username: '',
      password: '',
      nickname: '',
    },
    loginObj: {
      username: '',
      password: '',
    }
  }),
  methods: {
    handleRegister () {
      register(this.registerObj).then(res => {
        const {data} = res
        if (data.code === 0) {
          alert('注册成功')
          this.curType = TYPE.LOGIN
        } else {
          alert('注册失败，原因：' + data.msg)
        }
      }).catch(err => console.error(err))
    },
    changeType (e, type) {
      e.preventDefault()
      this.curType = type
    },
    handleLogin () {
      login(this.loginObj).then(res => {
        const {data} = res
        if (data.code === 0) {
          alert('登录成功')
          this.$router.push('/home')
        } else {
          alert('登录失败，原因：' + data.msg)
        }
      }).catch(err => console.error(err))
    }
  },
}
</script>

<style scoped>

</style>